import dash
from dash import dcc, html, callback, Output, Input, State
import dash_bootstrap_components as dbc
import markdown
import os
from openai import OpenAI
import time

# 初始化Dash应用
app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])
app.title = 'DeepSeek 解释助手'

# 读取提示词文件
with open('prompt.md', 'r', encoding='utf-8') as f:
    system_prompt = f.read()

# 读取环境变量中的API密钥或使用默认密钥
api_key = os.getenv('DEEPSEEK_API_KEY', 'sk-751ae345bc8440f48b5231ed222409b8')

# 应用布局
app.layout = dbc.Container([
    dbc.Row([
        dbc.Col([
            html.H1('DeepSeek 解释助手', className='text-center mt-4 mb-4'),
            html.P('输入您想要解释的内容，点击按钮获取AI生成的解释。', className='text-center text-muted mb-4')
        ], width=12)
    ]),
    
    dbc.Row([
        dbc.Col([
            dcc.Textarea(
                id='user-input',
                placeholder='请输入您想要解释的内容...',
                style={'width': '100%', 'height': 200, 'resize': 'vertical'},
                className='form-control'
            ),
            dbc.Button('开始解释', id='explain-button', color='primary', className='mt-2', style={'width': '100%'})
        ], width=12, md=6)
    ]),
    
    dbc.Row([
        dbc.Col([
            html.Div(id='output-container', className='mt-4 p-4 border rounded bg-light')
        ], width=12)
    ]),
    
    dbc.Row([
        dbc.Col([
            dcc.Loading(
                id='loading-indicator',
                type='default',
                children=html.Div(id='loading-output', style={'display': 'none'})
            )
        ], width=12)
    ])
], fluid=True)

# 回调函数
@app.callback(
    Output('output-container', 'children'),
    Input('explain-button', 'n_clicks'),
    State('user-input', 'value'),
    prevent_initial_call=True
)
def generate_explanation(n_clicks, user_input):
    if not user_input or user_input.strip() == '':
        return html.Div('请输入内容后再点击解释按钮。', className='text-danger')
    
    try:
        # 初始化OpenAI客户端
        client = OpenAI(api_key=api_key, base_url="https://api.deepseek.com")
        
        # 准备消息
        messages = [
            {"role": "system", "content": system_prompt},
            {"role": "user", "content": user_input},
        ]
        
        # 显示加载状态
        loading_div = html.Div([
            dbc.Spinner(color="primary", type="border"),
            html.Span(" AI正在生成解释...", style={'marginLeft': '10px'})
        ])
        
        # 发送请求
        response = client.chat.completions.create(
            model="deepseek-chat",
            messages=messages,
            stream=False
        )
        
        # 获取响应内容
        explanation = response.choices[0].message.content
        
        # 保存为MD文件
        timestamp = time.strftime("%Y%m%d_%H%M%S")
        filename = f"explanation_{timestamp}.md"
        with open(filename, 'w', encoding='utf-8') as f:
            f.write(f"# 解释内容\n\n{explanation}")
        
        # 渲染Markdown为HTML
        html_content = markdown.markdown(explanation)
        
        # 返回结果和文件名信息
        result_div = html.Div([
            html.H3('解释结果', className='mt-2 mb-3'),
            html.Div([
                html.Small(f'解释已保存为: {filename}', className='text-muted')
            ], className='mb-3'),
            html.Div(html_content, dangerously_allow_html=True)
        ])
        
        return result_div
        
    except Exception as e:
        error_message = f"生成解释时出错: {str(e)}"
        return html.Div(error_message, className='text-danger')

if __name__ == '__main__':
    app.run(debug=True, port=8050)